package xyz.coolcsm.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.*;
import xyz.coolcsm.security.service.*;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 什锦
 * @since 2021-06-1
 */

@RestController
public class UserController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserInfoService sysUserInfoService;

    @Autowired
    BlogService blogService;

    @Autowired
    QuestionService questionService;

    @Autowired
    CommentService commentService;

    @Autowired
    RsaKeyProperties prop;

    @Autowired
    RedisService redisService;

    //返回个人信息
   @PostMapping("/api/user/userInfo")
   public JsonResult sysUserInfoCallBack(HttpServletRequest request){
       //获取个人基本信息
       String token = request.getHeader("Authorization");
       Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
               prop.getPublicKey(), SysUser.class);
       SysUser user = payload.getUserInfo();
       String uid = user.getId().toString();
       //缓存查询个人信息
       SysUserInfo userInfo =(SysUserInfo) redisService.get(user.getId().toString());
       userInfo.setEmail(user.getEmail());
       // 获取用户的问题，博客，回复数
       int blogCount = blogService.count(new QueryWrapper<Blog>().eq("author_id", uid));
       int questionCount = questionService.count(new QueryWrapper<Question>().eq("author_id", uid));
       int commentCount = commentService.count(new QueryWrapper<Comment>().eq("user_id", uid));
       userInfo.setBlogCount(blogCount);
       userInfo.setQuestionCount(questionCount);
       userInfo.setCommentCount(commentCount);
       return ResultTool.success(userInfo);
    }


    //上传图片，并返回逻辑路径
    @CrossOrigin
    @PostMapping("/api/user/avatar")
    public String coversUpload(MultipartFile file) throws Exception{
        String filename = "sj-"+ UUID.randomUUID().toString().replaceAll("-", "");
        String folder = "E:/前端代码测试/apply/img";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, filename + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8080/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    //更新头像
    @PostMapping("/api/user/updateAvatar")
    public JsonResult updateAvatar(HttpServletRequest request,@RequestBody SysUser sysUser){
       //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        sysUser.setId(payload.getUserInfo().getId());
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setUid(payload.getUserInfo().getId().toString());
        sysUserInfo.setAvatar(sysUser.getAvatar());
        //更新数据库
        sysUserService.update(sysUser);
        sysUserInfoService.updateById(sysUserInfo);
        //更新缓存
        redisService.set(payload.getUserInfo().getId().toString(),sysUserInfoService.getById(payload.getUserInfo().getId()));
        return ResultTool.success();
    }

    @PostMapping("/api/user/updateUserInfo")
    public JsonResult updateUserInfo(@RequestBody SysUserInfo sysUserInfo){
        //更新个人信息数据库
        sysUserInfoService.updateById(sysUserInfo);
        SysUserInfo byId = sysUserInfoService.getById(sysUserInfo.getUid());
        //更新缓存
        redisService.set(sysUserInfo.getUid(),byId);
        return ResultTool.success();
    }
}
